package net.recursv.motific.ant

import org.apache.tools.ant.BuildException
import org.apache.tools.ant.taskdefs.condition.Condition

/**
 * Created by: recursv
 * Date: 28/08/2009
 * Time: 9:40:56 AM
 */
class RequiresCompile implements Condition {
  List<File> _sources = new ArrayList<File>()
  File _target
  String _source

  public boolean eval() {
    validate();

    if (!_target.exists())
      return true;

    File root = new File(_source)

    if (root.isDirectory()) {
      return test(root, _target.lastModified());
    } else {
      return root.lastModified() > _target.lastModified();
    }
  }

  private boolean test(File path, long timestamp) {
    for (String s: (path.list() as List<String>)) {
      File f = new File(path, s)
      if (f.isDirectory()) {
        if (f.getName() != ".svn" && test(f, timestamp)) {
          return true
        }
      } else if (f.lastModified() > timestamp)
        return true
    }
    return false;
  }

  private void validate() {
    if (_target == null)
      throw new BuildException("attribute target must point to the compiled archieve")

    if (_source == null)
      throw new BuildException("Attribute source must point to the base source directory")
  }

  public void setTarget(String jar) {
    _target = new File(jar)
  }

  public void setSource(String dir) {
    _source = dir;
  }

}
